<template>
  <div class="main-box">
    <div class="table-box">
      <div class="card mb10 pt0 pb0">
        <SelectFilter :data="selectFilterData" :default-values="selectFilterValues" @change="changeSelectFilter" />
      </div>
      <ProTable
        ref="proTable"
        title="用户列表"
        highlight-current-row
        :columns="columns"
        :request-api="getUserList"
        :init-param="Object.assign(initParams, selectFilterValues)"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" :icon="CirclePlus" @click="openAddDrawer('新增')">新增用户</el-button>
          <el-button type="primary" :icon="Upload" plain @click="batchAdd">批量添加用户</el-button>
          <el-button type="primary" :icon="Download" plain @click="downloadFile">导出用户数据</el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
          <el-button type="primary" link :icon="Refresh" @click="resetPass(scope.row)">重置密码</el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
        </template>
      </ProTable>
      <UserDrawer ref="drawerUserRef" />
      <UserAddDrawer ref="drawerUserAddRef" />
      <ImportExcel ref="dialogRef" />
    </div>
  </div>
</template>
<script setup lang="tsx" name="useSelectFilter">
import { ref, reactive, onMounted } from "vue";
import { User } from "@/api/interface";
import { ElMessage, ElMessageBox } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { genderType, userStatus, userRole } from "@/utils/serviceDict";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "./components/UserDrawer.vue";
import UserAddDrawer from "./components/UserAddDrawer.vue";
import SelectFilter from "@/components/SelectFilter/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import {
  getUserList,
  deleteUser,
  editUser,
  addUser,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser,
  changeUserStatus
} from "@/api/modules/user";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns: ColumnProps[] = [
  { prop: "userId", label: "id", width: 80, sortable: true },
  { prop: "username", label: "用户账号", width: 120 },
  { prop: "name", label: "姓名", width: 80, search: { el: "input" } },
  { prop: "userGender", label: "性别", width: 80, sortable: true, enum: genderType },
  { prop: "userIdentity", label: "身份证号", width: 150, search: { el: "input" } },
  { prop: "departmentName", label: "部门名称", search: { el: "input" } },
  { prop: "userRole", label: "身份", width: 120, sortable: true, tag: true, enum: userRole },
  // { prop: "status", label: "用户状态", width: 120, sortable: true, tag: true, enum: userStatus },
  {
    prop: "userStatus",
    label: "用户状态",
    enum: userStatus,
    fieldNames: { label: "userLabel", value: "userStatus" },
    render: scope => {
      return (
        <>
          {
            <el-switch
              model-value={scope.row.userStatus}
              active-text={scope.row.userStatus ? "启用" : "禁用"}
              active-value={1}
              inactive-value={0}
              onClick={() => changeStatus(scope.row)}
            />
          }
        </>
      );
    }
  },
  // { prop: "createTime", label: "创建时间", width: 180, sortable: true },
  { prop: "operation", label: "操作", width: 330, fixed: "right" }
];

// selectFilter 数据（用户角色为后台数据）
const selectFilterData = reactive([
  {
    title: "用户身份",
    key: "userRole",
    options: [
      {
        label: "全部",
        value: -1
      },
      {
        label: "客服中心",
        value: 1,
        icon: "UserFilled"
      },
      {
        label: "调度中心",
        value: 2,
        icon: "UserFilled"
      },
      {
        label: "中心库房",
        value: 3,
        icon: "UserFilled"
      },
      {
        label: "分站库房",
        value: 4,
        icon: "UserFilled"
      },
      {
        label: "分站",
        value: 5,
        icon: "UserFilled"
      },
      {
        label: "配送中心",
        value: 6,
        icon: "UserFilled"
      },
      {
        label: "财务部",
        value: 7,
        icon: "UserFilled"
      },
      {
        label: "配送员",
        value: 8,
        icon: "UserFilled"
      }
    ]
  }
]);

// 获取用户角色字典
onMounted(() => {});

const initParams = ref({ id: 1 });
// 默认 selectFilter 参数
const selectFilterValues = ref({ userRole: -1 });
const changeSelectFilter = (value: typeof selectFilterValues.value) => {
  ElMessage.success("筛选完成");
  proTable.value!.pageable.current = 1;
  selectFilterValues.value = value;
};

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(deleteUser, { userId: params.userId }, `删除【${params.name}】用户`);
  proTable.value?.getTableList();
};

// 重置用户密码
const resetPass = async (params: User.ResUserList) => {
  await useHandleData(resetUserPassWord, { userId: params.userId }, `重置【${params.name}】用户密码`);
  proTable.value?.getTableList();
};

// 切换用户状态
const changeStatus = async (row: User.ResUserList) => {
  await useHandleData(
    changeUserStatus,
    { userId: row.userId, status: row.userStatus == 1 ? 0 : 1 },
    `切换【${row.username}】用户状态`
  );
  proTable.value?.getTableList();
};

// 导出用户列表
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(exportUserInfo, "用户列表", proTable.value?.searchParam)
  );
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "用户",
    tempApi: exportUserInfo,
    importApi: BatchAddUser,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};

// 打开 drawer(查看、编辑)
const drawerUserRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<User.ResUserList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addUser : title === "编辑" ? editUser : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerUserRef.value?.acceptParams(params);
};

// 打开 drawer(新增)
const drawerUserAddRef = ref<InstanceType<typeof UserAddDrawer> | null>(null);
const openAddDrawer = (title: string) => {
  const params = {
    title,
    isView: false,
    api: addUser,
    getTableList: proTable.value?.getTableList
  };
  drawerUserAddRef.value?.acceptParams(params);
};
</script>
